package com.yxsk.relay.job.admin.core.trigger.listener;

import com.yxsk.relay.job.admin.core.schedule.quartz.context.TriggerContext;
import com.yxsk.relay.job.admin.data.entity.JobTriggerLog;
import com.yxsk.relay.job.admin.data.service.JobTriggerLogService;
import com.yxsk.relay.job.component.common.utils.ExceptionUtils;
import com.yxsk.relay.job.component.common.vo.ExecuteResult;
import com.yxsk.relay.job.component.common.vo.TriggerResult;
import lombok.AllArgsConstructor;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 18:36
 * @Description
 */
@AllArgsConstructor
public class QuartzTriggerListener implements TaskTriggerListener {

    private JobTriggerLogService triggerLogService;

    @Override
    public void beforeTrigger(TriggerContext context) {
        // 添加触发日志
        JobTriggerLog log = buildTriggerLog(context);
        log.setTriggerResultCode(TriggerResult.TriggerResultCode.TRIGGERING.getCode());
        triggerLogService.addEntity(log);
    }

    @Override
    public void afterComplete(TriggerContext context, TriggerResult triggerResult) {
        // 更新触发日志
        JobTriggerLog triggerLog = buildTriggerLog(context);
        triggerLog.setTriggerResultCode(triggerResult.getCode());
        triggerLog.setTriggerResultMessage(triggerResult.getErrorMsg());
        triggerLogService.updateById(triggerLog);
    }

    @Override
    public void onError(TriggerContext context, Throwable e) {
        // 更新触发日志
        JobTriggerLog triggerLog = buildTriggerLog(context);
        triggerLog.setTriggerResultCode(ExecuteResult.ExecuteResultCode.ERROR.getCode());
        triggerLog.setTriggerResultMessage(ExceptionUtils.getStackInfo(e));
        triggerLogService.updateById(triggerLog);
    }

    private JobTriggerLog buildTriggerLog(TriggerContext context) {
        JobTriggerLog triggerLog = new JobTriggerLog();
        triggerLog.setId(context.getTriggerInfo().getTriggerId());
        triggerLog.setJobId(context.getTriggerInfo().getJobId());
        triggerLog.setTriggerParam(context.getTriggerInfo().getTriggerParam());
        triggerLog.setTriggerResultCode(context.getTriggerInfo().getTriggerResultCode());
        triggerLog.setTriggerResultMessage(context.getTriggerInfo().getTriggerResultMessage());
        triggerLog.setTriggerTime(context.getTriggerInfo().getBeginTime());
        triggerLog.setTriggerEndTime(context.getTriggerInfo().getEndTime());
        triggerLog.setExecuteLogId(context.getTriggerInfo().getExecuteLogId());
        return triggerLog;
    }

}
